<template>
  <div class="voice">
    <audio id="player" :src="Mp3url" controls autoplay style="position: absolute; z-index: -1"></audio>
    <div class="voice-lef">
      <div class="voice-main">
        <div class="voice-title">
          <span>客户类型（一）</span>
        </div>
        <div class="helloCss">欢迎进入考试阶段，本次考试总共15分钟。请仔细阅读客户信息后，点击开始考试。</div>
        <div class="userInfo">
          <h2>客户信息</h2>
          <div class="userInfoCss">
            <p>客户吴涛，男，37岁，现任某公司职员</p>
            <p>车辆信息：宝马320，上次保养公里数为2万公里，进行了发动机的基础保养。</p>
            <p>本次收到远程售后提醒：保养灯亮黄灯机，目前公里数为29710km，每周平均行驶200公里，距离下次保养剩余290km，大约剩余10天</p>
            <p>目前店内空闲的时段为周六上午10：00或下午3：00</p>
          </div>
        </div>
      </div>
      <div class="voice-btn">
        <span @click="startRecording" v-show="!StartVoice">开始考试</span>
        <span @click="endExamFun" class="spanCss" v-show="StartVoice">结束考试</span>
      </div>
      <div class="YYcontentCSS">
        <!-- 容器 -->
        <div class="YYcontent" ref="Maincontxt" id="Maincontxt">
          <ul>
            <li v-for="(item, index) in ContxtList" :key="index" :class="item.user == 1 ? 'contextlef' : 'contextrig'">
              <img src="../assets/img/bwmuser.png" alt="" v-if="item.user == 1" style="margin-right: 12px" />
              <p v-show="item.contxt">{{ item.contxt }}</p>
              <img src="../assets/img/bmwlogo.png" alt="" v-if="item.user == 2" style="margin-left: 12px" />
            </li>
            <li class="contextrig" v-if="ContxtList.length % 2 != 0 && txtstr.contxt">
              <p>{{ txtstr.contxt.replace(/回电/g, '回店') }}</p>
              <img src="../assets/img/bmwlogo.png" alt="" style="margin-left: 12px" />
            </li>
          </ul>
        </div>

        <div class="send-btn" v-if="StartVoice == 1">
          <span @click="stopExam">{{ !isStopExam ? '停止说话' : '开始对话' }}</span>
        </div>
      </div>
    </div>
    <div class="voice-rig">
      <h3>视频框</h3>
      <div class="picimg">
        <img src="../assets/img/shexiang.png" alt="" v-show="!StartVoice" />
        <video id="videoCamera" :width="videoWidth" :height="videoHeight" autoplay></video>
        <canvas id="canvasCamera" :width="videoWidth" :height="videoHeight" style="display: none"></canvas>
      </div>
      <br />
      <p>
        <span>当前表情</span>
        <i>{{ assetsData.emotionName[ShowExpressionList[ShowExpressionList.length - 1]] || '中性' }}</i>
      </p>

      <p>
        <span>剩余时间</span>
        <i>{{ user.timer }}</i>
      </p>
      <h3 style="margin-top: 40px">实时状态</h3>
      <p>
        <span>考核点触发</span>
        <i>{{ AssessmentList.length || 0 }}个</i>
      </p>
      <p>
        <span>违禁词触发</span>
        <i>{{ SensitiveWordsArr.length || 0 }}个</i>
      </p>
    </div>
  </div>
</template>
<script>
import Recorder from '../utils/recorder.js';
import assetsData from '../utils/assets.js';

const recorder = new Recorder({
  sampleBits: 16, // 采样位数，支持 8 或 16，默认是16
  sampleRate: 16000, // 采样率，支持 11025、16000、22050、24000、44100、48000，根据浏览器默认值，我的chrome是48000
  numChannels: 1, // 声道，支持 1 或 2， 默认是1
  compiling: true, //(0. x版本中生效, 1. x增加中) // 是否边录边转换，默认是false
});
var SOCKET = null;
// 防抖
const delay = (function () {
  let timer = 0;
  return function (callback, ms) {
    clearTimeout(timer);
    timer = setTimeout(callback, ms);
  };
})();

// function getCookie(name) {
//   var arr,
//     reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)');
//   if ((arr = document.cookie.match(reg))) return unescape(arr[2]);
//   else return null;
// }
// var str = getCookie('wxglweb');
// var cookie = str.split('&')[1];
// var cid = cookie.split('=')[1];

// var Loading = null;

// expression(none: 不笑； smile: 微笑； laugh: 大笑), emotion(angry: 愤怒 disgust: 厌恶 fear: 恐惧 happy: 高兴 sad: 伤心 surprise:
//     惊讶 neutral: 无表情 pouty: 撅嘴 grimace: 鬼脸)
// 表情
const expression = {
  none: '不笑',
  smile: '微笑',
  laugh: '大笑',
};

const emotion2 = {
  none: '10',
  smile: '50',
  laugh: '30',
  angry: '-10',
  disgust: '-30',
  fear: '-10',
  happy: '50',
  sad: '-10',
  surprise: '0',
  neutral: '0',
  pouty: '0',
  grimace: '0',
};
const emotion = {
  angry: '愤怒',
  disgust: '厌恶',
  fear: '恐惧',
  happy: '高兴',
  sad: '伤心',
  surprise: '惊讶',
  neutral: '无表情',
  pouty: '撅嘴',
  grimace: '鬼脸',
};

export default {
  data() {
    return {
      // info: {},
      examType: 4, //试卷id
      assetsData: assetsData,
      vol: '', // 声音大小
      StopVoice: null,
      info: {
        vtype: '首次进店',
        username: '',
        cartype: '宝马',
        lx: '场景1', // 考试类型
      },
      expression: expression,
      emotion: emotion,
      ExpressionList: [], //表情列表
      ExpressionContent: '', //表情
      ShowExpressionList: [], // 表情曲线
      PhotoAdmin: 1,
      StartExam: 2, // 是否开始考试
      examid: '', // 考试id
      RecorderAdmin: 1, // 摄像头是否可用 语音是否可用 0 不可用
      StartVoice: 0, // 是否开始录音
      vociedata: '', // 录音数据
      chunk: 0, // 当前切片
      vtypelist: [], // 职位列表
      usernamelist: [], // 人员列表
      cartypelist: [], // 车系列表

      //  摄像头
      videoWidth: 200,
      videoHeight: 200,
      imgSrc: '', // 摄像头图像路径
      thisCancas: null,
      thisContext: null,
      thisVideo: null,

      beginloading: false, // 是否开始录音
      isSocket: false, //是否有心跳
      timertxt: null,
      txtstr: {
        starttime: '',
        endtime: '',
        user: '',
        id: '',
        contxt: '',
        endobj: {},
      },
      // 语音文本列表
      ContxtList: [],
      // 语音
      //   用户信息
      timer: null, // 时间
      Mp3url: '', //  Mp3url  语音播放
      user: {
        timer: '',
      },
      nowdate: 900000, //倒计时    10分钟
      isStopExam: false, // 是否暂停考试
      showtxt: '',
      Serves: false,
      nowtxt: '', //正在说的话术
      SpeakSpeed: [],
      issocketclose: true, //长连接是否断开
      ShowMask: false,
      VadioEnd: false,

      AssessmentList: [], // 触发的考核点
      SensitiveWordsArr: [], //   违规词
      isscoll: true,
    };
  },
  methods: {
    // 开始考试
    BenginExam() {
      let data = {
        cid: 'bztest',
        vtype: this.info.vtype,
        username: this.info.username,
        cartype: this.info.cartype,
      };
      // if (this.RecorderAdmin === 0) {
      //   alert('麦克风初始化失败，请同意使用麦克风！');
      //   // return
      // }
      // if (this.PhotoAdmin === 0) {
      //   alert('调用摄像头失败，请检查是否连接摄像头！');
      //   // return
      // }

      this.$axios.Postdata('manage/Voicerecordreport.asmx/createExam', { data: JSON.stringify(this.$Help.QMdata(data)) }).then(res => {
        console.log(res);
        if (res.errcode === 0) {
          this.examid = res.examid || '';
          localStorage.setItem('examid', res.examid);

          this.StartExam = 2;
        }
      });
      // $.ajax({
      //   type: 'post',
      //   url: `${url}/manage/Voicerecordreport.asmx/createExam`,
      //   data: {
      //     data: JSON.stringify(QMdata(data)),
      //   },
      //   dataType: 'json',
      //   success: res => {
      //     console.log(res);
      //     if (res.errcode === 0) {
      //       this.examid = res.examid;
      //       this.StartExam = 2;
      //     }
      //   },
      // });
    },

    // 调用权限（打开摄像头功能）
    getCompetence() {
      var _this = this;
      this.thisCancas = document.getElementById('canvasCamera');
      this.thisContext = this.thisCancas.getContext('2d');
      this.thisVideo = document.getElementById('videoCamera');
      // 旧版本浏览器可能根本不支持mediaDevices，我们首先设置一个空对象
      if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {};
      }
      // 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象
      // 使用getUserMedia，因为它会覆盖现有的属性。
      // 这里，如果缺少getUserMedia属性，就添加它。
      console.log(navigator.mediaDevices);
      if (navigator.mediaDevices.getUserMedia === undefined) {
        navigator.mediaDevices.getUserMedia = function (constraints) {
          // 首先获取现存的getUserMedia(如果存在)
          var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.getUserMedia;
          // 有些浏览器不支持，会返回错误信息
          console.log(getUserMedia);
          // 保持接口一致
          if (!getUserMedia) {
            return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
          }
          // 否则，使用Promise将调用包装到旧的navigator.getUserMedia
          return new Promise(function (resolve, reject) {
            getUserMedia.call(navigator, constraints, resolve, reject);
          });
        };
      }
      var constraints = {
        audio: false,
        video: {
          width: this.videoWidth,
          height: this.videoHeight,
          transform: 'scaleX(-1)',
          facingMode: 'user',
        },
      };
      navigator.mediaDevices
        .getUserMedia(constraints)
        .then(function (stream) {
          // 旧的浏览器可能没有srcObject
          if ('srcObject' in _this.thisVideo) {
            _this.thisVideo.srcObject = stream;
          } else {
            // 避免在新的浏览器中使用它，因为它正在被弃用。
            _this.thisVideo.src = window.URL.createObjectURL(stream);
          }
          _this.thisVideo.onloadedmetadata = function (e) {
            _this.thisVideo.play();
          };
        })
        .catch(err => {
          console.log(err);
          this.PhotoAdmin = 0;
          alert('调用摄像头失败，请检查是否连接摄像头！');
        });
    },
    //  绘制图片（拍照功能）

    setImage() {
      if (this.VadioEnd) return;
      var _this = this;
      // 点击，canvas画图
      _this.thisContext.drawImage(_this.thisVideo, 0, 0, _this.videoWidth, _this.videoHeight);
      // 获取图片base64链接
      var image = this.thisCancas.toDataURL('image/jpeg');
      //  base64 转文件流

      let imgdata = _this.dataURLtoFile(image, `${new Date().getTime()}.png`);

      // 上传图片
      this.UploadImageFun(imgdata);
    },
    // base64转文件

    dataURLtoFile(dataurl, filename) {
      var arr = dataurl.split(',');
      var mime = arr[0].match(/:(.*?);/)[1];
      var bstr = atob(arr[1]);
      var n = bstr.length;
      var u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, {
        type: mime,
      });
    },

    // 暂停录音
    stopExam() {
      let that = this;
      if (that.isStopExam) {
        console.log('开始说话');
        // 打开长连接
        that.openWebSocket();
        that.isStopExam = false;
        that.countdown(that.nowdate);
        // 服务请求结束
        setTimeout(() => {
          that.txtstr.id = new Date().getTime();
          that.txtstr.endobj = {};
        }, 1000);
      } else {
        console.log('暂停说话');
        SOCKET.send(
          JSON.stringify({
            type: 'end',
          })
        );
        that.isStopExam = true;
        SOCKET.close();
        if (!this.txtstr.contxt) return;
        setTimeout(() => {
          this.ContxtList.push({
            user: 2,
            id: this.txtstr.id,
            contxt: this.txtstr.contxt,
          });
          //  终止这段话，然后获取回术
          that.GetAnswerSentenceFun();
        }, 1000);
      }
    },

    // 关闭摄像头
    stopNavigator() {
      console.log(this.thisVideo);
      this.thisVideo.srcObject.getTracks()[0].stop();
    },

    //  处理语音转译
    Pcontent(data) {
      let txt = '';
      let timerarr = [];
      // 取 key
      for (let key in data.endobj) {
        timerarr.push(key);
      }
      // 排序
      timerarr.sort(function (a, b) {
        return a - b;
      });
      txt = '';
      timerarr.forEach(item2 => {
        txt += data.endobj[item2];
      });
      data.contxt = txt.replace(/回电/g, '回店');
      this.SpeakSpeed.push(Math.ceil((data.contxt.length / (data.endtime - data.starttime || 0)) * 1000));
      // this.DrowEcharts(
      //   {
      //     time: '',
      //     DataArray: this.SpeakSpeed,
      //   },
      //   '2'
      // );
      // console.log(data);
    },
    // 添加内容    文字处理
    Putcontext(data) {
      let that = this;
      // console.log(data)
      let flag = false;
      this.ContxtList.forEach(item => {
        if (item.id == data.id) {
          flag = true;
        }
        if (item.user == 2) {
          let timerarr = [];
          // 取 key
          for (let key in item.endobj) {
            timerarr.push(key);
          }
          // 排序
          timerarr.sort(function (a, b) {
            return a - b;
          });
          item.starttime = timerarr[0];
          item.contxt = '';
          timerarr.forEach(item2 => {
            item.contxt += item.endobj[item2];
          });
        }
      });
      if (!flag) {
        this.ContxtList.push(data);
      }
    },

    // 开始录音
    startRecording: function () {
      recorder.start().then(
        () => {
          // 开始录音
          console.log('录音已开始');
          this.countdown(this.nowdate); // 开始考试倒计时开始
          let that = this;
          that.ContxtList.push({
            user: 1,
            id: new Date().getTime(),
            contxt: '喂',
          });
          this.open = 2;
          this.isStopExam = true;
          that.StartVoice = 1;
          that.openWebSocket();

          // 定时上传图片
          setTimeout(() => {
            that.setImage();
          }, 3000);
        },
        error => {
          // 出错了
          console.log(`${error.name} : ${error.message}`);
        }
      );
    },

    // 停止录音
    stopRecording: function () {
      recorder.stop();
      this.beginloading = false;
      console.log('停止录音');
      // clearInterval(this.timertxt)
      this.StartVoice = 0;
      // 结束
      SOCKET.send(
        JSON.stringify({
          type: 'end',
        })
      );
      this.endExamFun();
    },

    // 开始倒计时
    countdown(timer) {
      // timer     结束时间
      if (this.isStopExam) return;
      const end = new Date().getTime() + this.nowdate;
      const now = new Date().getTime();
      const msec = end - now;
      if (msec < 0) return;
      const that = this;
      setTimeout(() => {
        that.user.timer = new Date(msec).Format('mm:ss');
        this.nowdate = end - new Date().getTime();
        that.countdown();
      }, 1000);
    },

    // 播放 Mp3
    PlayerMp3(data) {
      var player = new Audio(data);
      player.play();
    },

    //  终止一句话
    stopvoiceFun() {
      if (!this.txtstr.contxt) return;
      // 修改
      if (this.nowtxt) {
        this.ContxtList.push({
          user: 2,
          id: this.txtstr.id,
          contxt: this.nowtxt,
        });
      } else {
        this.ContxtList.push({
          user: 2,
          id: this.txtstr.id,
          contxt: this.txtstr.contxt,
        });
      }

      // console.log('停止录音')
      //  终止这段话，然后获取回术
      this.GetAnswerSentenceFun();
    },

    //  链接socket
    openWebSocket() {
      let that = this;

      if ('WebSocket' in window) {
        // let data = {
        //   Appid: '5bea7197',
        //   SecretId: 'e819385d699fa9f2fb5a07266844f0c8',
        // };
        // // const obj = that.$Help.KDFun(data);
        // const obj = that.$Help.KDFun(data);
        // console.log(obj);
        // SOCKET = new WebSocket(`wss://rtasr.xfyun.cn/v1/ws?appid=${data.Appid}&ts=${obj.timestamp}&signa=${obj.signature}=&pd=car`);

        let data = {
          Appid: '1256599233',
          SecretId: 'AKIDBahiZEs2BDFByhRdyAf5KNEvmdOzCnup',
        };
        const obj = that.$Help.QMFun(data);
        SOCKET = new WebSocket(`wss://${obj.SecretKey}&signature=${obj.signature}`);
        console.log('链接成功');
      } else {
        console.log('当前浏览器 Not support websocket');
        // return
      }
      SOCKET.onopen = res => {
        console.log('已连接');
        let that = this;
        that.issocketclose = false;
        // let voice = recorder.getNextData();
        // console.log(voice);
        that.timertxt = setInterval(() => {
          let voice = recorder.getNextData();
          if (that.issocketclose) return;
          if (voice.length != 0) {
            if (voice.length >= 2) {
              voice.forEach(element => {
                SOCKET.send(element);
              });
            } else {
              SOCKET.send(voice[0]);
            }
          }
        }, 40);
      };

      // 接收信息
      (SOCKET.onmessage = res => {
        // console.log(res.data);
        let that = this;
        const data = JSON.parse(res.data);
        if (that.isStopExam || !data.result.voice_text_str) return;
        if (data.result.voice_text_str) {
          this.txtstr.endtime = data.result.end_time;
          this.txtstr.endobj[data.result.start_time] = data.result.voice_text_str;
          this.txtstr.user = 2;

          this.Pcontent(this.txtstr);

          this.showtxt = this.txtstr;
        }
      }),
        // socket  关闭
        (SOCKET.onclose = res => {
          console.log('SOCKET暂时关闭');
          that.issocketclose = true;
          if (that.StartVoice === 1 && !that.isStopExam) {
            // 正在录音
            that.openWebSocket();
          }
        }),
        (SOCKET.onerror = () => {
          // 连接错误
          console.log('连接错误');
        });
    },

    // 提交分片数据
    uploadVoiceFun(byts) {
      let data1 = {
        examid: this.examid,
        chunk: byts.chunk,
      };
      let formdata = new FormData();
      formdata.append('byte', byts.byts);
      formdata.append('data', JSON.stringify(this.$Help.QMdata(data1)));
      this.$axios.formatPostData('manage/Voicerecordreport.asmx/uploadVoice', formdata).then(res => {
        if (res.errcode != 0) {
          // 上传错误重新上传
          this.uploadVoiceFun(byts);
        }
      });

      // $.ajax({
      //   type: 'post', //默认get
      //   url: `${url}/manage/Voicerecordreport.asmx/uploadVoice`, //默认当前页
      //   data: formdata,
      //   dataType: 'json',
      //   cache: false,
      //   processData: false,
      //   contentType: false,
      //   success: res => {
      //     //请求成功回调
      //     console.log(res);
      //     if (res.errcode != 0) {
      //       // 上传错误重新上传
      //       this.uploadVoiceFun(byts);
      //     }
      //   },
      //   error: function (e) {
      //     //请求超时回调
      //     if (e.statusText == 'timeout') {
      //       alert('请求超时');
      //     }
      //   },
      // });
    },

    //  获取动态人物表情
    getExamEmotionFun() {
      let data = {
        examid: this.examid,
      };

      this.$axios
        .Postdata('manage/Voicerecordreport.asmx/getExamEmotion', {
          data: JSON.stringify(this.$Help.QMdata(data)),
        })
        .then(res => {
          //请求成功回调
          // console.log(res)
          let DataArray = [];
          let time = [];
          // 处理表情
          res.forEach(item => {
            this.ExpressionList.forEach(item2 => {
              if (item2.count != item.count && item.emotion == item2.emotion) {
                this.ShowExpressionList.push(item.emotion);
              }
            });
            let idx = this.ExpressionList.findIndex(item3 => item.emotion != item3);
            if (idx == -1) {
              this.ShowExpressionList.push(item.emotion);
            }
          });
          this.ExpressionList = res;
          // let ShowExpressionListCopy = this.ShowExpressionList
          if (!this.isStopExam) {
            this.ShowExpressionList.forEach((item, index) => {
              if (item) {
                DataArray.push(emotion2[item] || '0');
              } else {
                DataArray.push(0);
              }
              time.push(index + 1);
            });
          }
          // // 绘制统计图
          // this.DrowEcharts(
          //   {
          //     time: time,
          //     DataArray: DataArray,
          //   },
          //   '1'
          // );
          setTimeout(() => {
            this.setImage();
          }, 2000);
        });

      // $.ajax({
      //   type: 'POST', //默认get
      //   url: `${url}/manage/Voicerecordreport.asmx/getExamEmotion`, //默认当前页
      //   data: {
      //     data: JSON.stringify(QMdata(data)),
      //   }, //格式{key:value}
      //   dataType: 'json',
      //   async: false,
      //   success: res => {
      //     //请求成功回调
      //     // console.log(res)
      //     let DataArray = [];
      //     let time = [];
      //     // 处理表情
      //     res.forEach(item => {
      //       this.ExpressionList.forEach(item2 => {
      //         if (item2.count != item.count && item.emotion == item2.emotion) {
      //           this.ShowExpressionList.push(item.emotion);
      //         }
      //       });
      //       let idx = this.ExpressionList.findIndex(item3 => item.emotion != item3);
      //       if (idx == -1) {
      //         this.ShowExpressionList.push(item.emotion);
      //       }
      //     });
      //     this.ExpressionList = res;
      //     // let ShowExpressionListCopy = this.ShowExpressionList
      //     if (!this.isStopExam) {
      //       this.ShowExpressionList.forEach((item, index) => {
      //         if (item) {
      //           DataArray.push(emotion2[item] || '0');
      //         } else {
      //           DataArray.push(0);
      //         }
      //         time.push(index + 1);
      //       });
      //     }
      //     // 绘制统计图
      //     this.DrowEcharts(
      //       {
      //         time: time,
      //         DataArray: DataArray,
      //       },
      //       '1'
      //     );
      //   },
      //   error: function (e) {
      //     //请求超时回调
      //     if (e.statusText == 'timeout') {
      //       alert('请求超时');
      //     }
      //   },
      //   complete: () => {
      //     // debugger
      //     setTimeout(() => {
      //       this.setImage();
      //     }, 2000);
      //   }, //无论请求是成功还是失败都会执行的回调，常用全局成员的释放，或者页面状态的重置
      // });
    },

    //  上传图片
    UploadImageFun(data) {
      let formdata = new FormData();
      formdata.append('image', data);
      formdata.append(
        'data',
        JSON.stringify(
          this.$Help.QMdata({
            examid: this.examid,
          })
        )
      );

      this.$axios.formatPostData('manage/Voicerecordreport.asmx/uploadExamJpg', formdata).then(res => {
        if (res.errcode == 0) {
          //  获取人物表情
          this.getExamEmotionFun();
        }
      });

      // $.ajax({
      //   type: 'POST', //默认get
      //   url: `${url}/manage/Voicerecordreport.asmx/uploadExamJpg`, //默认当前页
      //   data: formdata, //格式{key:value}
      //   cache: false,
      //   processData: false,
      //   contentType: false,
      //   dataType: 'json',
      //   success: res => {
      //     //请求成功回调
      //     console.log(res);
      //     // 上传成功
      //     if (res.errcode == 0) {
      //       //  获取人物表情
      //       this.getExamEmotionFun();
      //     }
      //   },
      //   error: function (e) {
      //     //请求超时回调
      //     if (e.statusText == 'timeout') {
      //       alert('请求超时');
      //     }
      //   },
      // });
    },

    //  录音 结束   提交总数据
    endExamFun() {
      recorder.stop();
      let data = {
        examid: this.examid,
        chunk: this.chunk,
        Txtcontent: ``,
        vtype: this.info.vtype,
        cid: 'bztest',
      };
      data.Txtcontent = this.ContxtFun(this.ContxtList);
      let blobdata = new Blob([recorder.getWAV()], {
        type: 'audio/wav',
      });

      let formdata = new FormData();
      formdata.append('byte', blobdata);
      formdata.append('data', JSON.stringify(this.$Help.QMdata(data)));

      this.$axios.formatPostData('manage/Voicerecordreport.asmx/endExam', formdata).then(res => {
        //请求成功回调
        if (res.errcode == 0) {
          this.VadioEnd = true;
          //  结束考试跳转页面
          this.exatEnd();
        }
      });

      // $.ajax({
      //   type: 'post', //默认get
      //   url: `${url}/manage/Voicerecordreport.asmx/endExam`, //默认当前页
      //   data: formdata,
      //   dataType: 'json',
      //   cache: false,
      //   processData: false,
      //   contentType: false,
      //   success: res => {
      //     //请求成功回调
      //     if (res.errcode == 0) {
      //       this.VadioEnd = true;
      //       this.$alert('', '考试信息上传成功', {
      //         confirmButtonText: '查看报告',
      //         showClose: false,
      //         callback: action => {
      //           this.ShowMask = true;
      //         },
      //       });
      //       // 显示成绩;
      //       // setTimeout(() => {}, 2000);
      //     }
      //   },
      //   error: function (e) {
      //     //请求超时回调
      //     if (e.statusText == 'timeout') {
      //       alert('请求超时');
      //     }
      //   },
      // });
    },

    // 语音内容处理

    ContxtFun(date) {
      let str = ``;
      date.forEach(item => {
        let timearr = [this.TimeProcessingFun(item.starttime), this.TimeProcessingFun(item.endtime)];
        let txt = `[${timearr}]  ${item.contxt}   \n`;
        str += txt;
      });
      return str;
    },
    //  时间处理   格式  1:1.000     1分1秒
    TimeProcessingFun(time) {
      if (time == 0) {
        return `0:0.00`;
      }
      let mm = Math.floor(time / 1000 / 60);
      let ss = (time - mm * 60000) / 1000;
      return `${mm}:${ss}`;
    },

    //  获取录音类型
    RecordingtypeFun() {
      this.$axios.Postdata('manage/Voicerecordreport.asmx/getvtype', { cid: 'bztest', actname: '' }).then(res => {
        console.log(res);
        this.vtypelist = res;
        this.info.vtype = res[0].vtype;
        this.GetusernameFun();
      });

      // $.ajax({
      //   type: 'post',
      //   url: `${url}/manage/Voicerecordreport.asmx/getvtype`,
      //   data: {
      //     cid: cid,
      //     actname: '',
      //   },
      //   dataType: 'json',
      //   success: res => {
      //     this.vtypelist = res;
      //     this.info.vtype = res[0].vtype;
      //     this.GetusernameFun();
      //   },
      // });
    },
    //  获取人员列表
    GetusernameFun() {
      this.$axios.Postdata('manage/Voicerecordreport.asmx/getusername', { cid: 'bztest', actname: '', vtype: this.info.vtype }).then(res => {
        console.log(res);
        this.info.username = res[0].username;
        this.usernamelist = res;
      });
      // $.ajax({
      //   type: 'post',
      //   url: `${url}/manage/Voicerecordreport.asmx/getusername`,
      //   data: {
      //     cid: cid,
      //     actname: '',
      //     vtype: this.info.vtype,
      //   },
      //   dataType: 'json',
      //   success: res => {
      //     this.info.username = res[0].username;
      //     this.usernamelist = res;
      //   },
      // });
    },

    //获取回术
    GetAnswerSentenceFun() {
      // debugger
      let that = this;
      that.Serves = true;
      let starttime = new Date().getTime();
      let sentence = '';
      this.ContxtList.forEach(item => {
        if (item.user == 2) {
          sentence = item.contxt;
        }
      });

      this.SensitiveWordsArr = assetsData.SensitiveWords(sentence, '2');
      let data = {
        data: JSON.stringify(
          this.$Help.QMdata({
            sentence: sentence,
            vtype: this.info.vtype,
            cartype: this.info.cartype,
            // paperid: 2, // 试卷类型
            paperid: this.examType,
            examid: this.examid, // 新增考试id
          })
        ),
      };

      this.$axios.Postdata('manage/Voicerecordreport.asmx/getAnswerSentence', data).then(res => {
        // if (res.errcode == 1) return;
        console.log(res);
        that.txtstr.contxt = '';
        this.AssessmentList = res.recogsentence ? res.recogsentence.split(',') : [];

        let MP3url = this.dataURLtoFile(`data:audio/mpeg;base64,` + res.audio, 'luyin');
        this.Mp3url = URL.createObjectURL(MP3url); // z转换 MP3播放
        let obj = {
          starttime: starttime,
          endtime: new Date().getTime(),
          user: 1,
          id: new Date().getTime(),
          contxt: res.sentence,
        };
        this.isscoll = false;
        that.ContxtList.push(obj);

        // 服务请求结束
        setTimeout(() => {
          that.txtstr = {
            starttime: '',
            endtime: '',
            user: '',
            id: '',
            contxt: '',
            endobj: {},
          };
          that.txtstr.id = new Date().getTime();
          that.Serves = false;
          this.isscoll = true;
        }, Math.ceil(res.sentence.length / 4 - 0) * 1000);
      });

      // $.ajax({
      //   type: 'post',
      //   url: `${url}/manage/Voicerecordreport.asmx/getAnswerSentence`,
      //   data: data,
      //   dataType: 'json',
      //   success: res => {
      //     that.txtstr.contxt = '';
      //     let MP3url = this.dataURLtoFile(`data:audio/mpeg;base64,` + res.audio, 'luyin');
      //     this.Mp3url = URL.createObjectURL(MP3url); // z转换 MP3播放
      //     let obj = {
      //       starttime: starttime,
      //       endtime: new Date().getTime(),
      //       user: 1,
      //       id: new Date().getTime(),
      //       contxt: res.sentence,
      //     };
      //     that.ContxtList.push(obj);

      //     // 服务请求结束
      //     setTimeout(() => {
      //       that.txtstr = {
      //         starttime: '',
      //         endtime: '',
      //         user: '',
      //         id: '',
      //         contxt: '',
      //         endobj: {},
      //       };
      //       that.txtstr.id = new Date().getTime();
      //       that.Serves = false;
      //     }, Math.ceil(res.sentence.length / 4 - 0) * 1000);
      //   },
      // });
    },

    DrowEcharts(data, type) {
      var dom;
      let yAxis = {
        type: 'value',
        // show: false,
        splitLine: {
          show: false, //不显示网格线
        },
      };
      if (type == 1) {
        yAxis.max = 50;
        yAxis.min = -50;
        dom = this.$refs.container;
      } else {
        dom = this.$refs.SpakeSpeedcss;
      }
      var echarts = require('echarts');
      let myChart = echarts.getInstanceByDom(dom);
      if (myChart == null) {
        // 如果不存在，就进行初始化
        myChart = echarts.init(dom);
      }

      // var myChart = echarts.init(dom);
      var app = {};
      var option;
      let ARRAYDATA = data.DataArray;
      if (type == 1) {
        if (data.DataArray.length > 10) {
          ARRAYDATA = ARRAYDATA.reverse()
            .filter((item, index, arr) => {
              return index < 10;
            })
            .reverse();
        }
      } else {
        if (data.DataArray.length > 20) {
          ARRAYDATA = ARRAYDATA.reverse()
            .filter((item, index, arr) => {
              return index < 20;
            })
            .reverse();
        }
      }
      option = {
        xAxis: {
          type: 'category',
          // data: data.time
          show: false, //不显示坐标轴线、坐标轴刻度线和坐标轴上的文字
          axisTick: {
            show: false, //不显示坐标轴刻度线
          },
          axisLine: {
            show: false, //不显示坐标轴线
          },
          axisLabel: {
            show: false, //不显示坐标轴上的文字
          },
        },
        grid: {
          left: '1%',
          right: '0%',
          bottom: '0%',
          containLabel: true,
        },
        yAxis: yAxis,
        series: [
          {
            data: ARRAYDATA,
            type: 'line',
            smooth: true,
            symbol: 'none',
          },
        ],
      };
      if (option && typeof option === 'object') {
        myChart.setOption(option);
      }
    },
    // 返回
    HistoryGoBack() {
      history.go(-1);
    },

    exatEnd() {
      localStorage.setItem('ShowExpressionList', JSON.stringify(this.ShowExpressionList)); //表情曲线列表
      localStorage.setItem('SpeakSpeed', JSON.stringify(this.SpeakSpeed)); //语速
      localStorage.setItem('ExpressionList', JSON.stringify(this.ExpressionList)); //表情触发次数
      this.$router.push({
        name: 'Result',
      });
    },
  },
  mounted() {
    let that = this;

    // 查看是否支持录音
    // console.log(Recorder, recorder);
    // this.$nextTick(function () {});
    Recorder.getPermission().then(
      () => {
        console.log('给权限了');
        this.RecorderAdmin = 1;
      },
      error => {
        console.log(`${error.name} : ${error.message}`);
      }
    );

    // 开始考试
    this.BenginExam();
    // 获取录音类型
    this.RecordingtypeFun();
    // 调用摄像头
    this.getCompetence();

    // this.startRecording();
  },

  // 更新数据周期
  updated() {
    if (this.isStopExam && this.isscoll) return;
    var Maincontxt = this.$refs.Maincontxt;
    Maincontxt.scrollTop = Maincontxt.scrollHeight;
  },

  watch: {
    vociedata: function (newVal, oldVal) {
      if (newVal.fileSize >= 1024 * 1024) {
        let blobdata = new Blob([recorder.getWAV()], {
          type: 'audio/wav',
        });
        const data = {
          chunk: this.chunk,
          byts: blobdata,
        };
        this.chunk++;
        // // 发送文件
        this.uploadVoiceFun(data);
      }
    },
  },

  created() {
    // console.log(JSON.parse(localStorage.getItem('checkedata')));
    // this.examType = JSON.parse(localStorage.getItem('checkedata')).checked1 ? 4 : 4;
    console.log(this.examType);
  },
};
</script>
<style lang="less" scoped>
.userInfoCss > p {
  position: relative;
  padding-left: 20px;
}
.userInfoCss > p::after {
  content: '';
  position: absolute;
  top: 50%;
  left: 10px;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  transform: translate(-50%, -50%);
  background-color: #368cf3;
}
.voice {
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
  height: 100%;
  width: 100%;
  overflow: hidden;
}
.voice-lef {
  flex: 1;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  padding: 8px;
}
.voice-rig {
  width: 260px;
  min-width: 260px;
  /* border-left: 8px solid #dedede; */
  box-sizing: border-box;
  padding: 8px 0;

  h3 {
    font-size: 18px;
    margin-top: 12px;
    font-weight: normal;
    box-sizing: border-box;
    position: relative;
    color: #7d7d7d;
    box-sizing: border-box;
    padding: 0 20px;
    margin: 20px 8px;
    &::after {
      content: '';
      position: absolute;
      top: 50%;
      left: 0;
      width: 9px;
      height: 9px;
      box-sizing: border-box;
      /* background-color: #368cf3; */
      border: 2px solid #368cf3;
      border-radius: 50%;
      transform: translateY(-50%);
    }
  }
  .picimg {
    width: 200px;
    height: 200px;
    background-color: #f1f3f5;
    border-radius: 50%;
    margin: 0 auto;
    position: relative;
    img {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
  }
  p {
    padding: 16px;
    display: flex;
    font-size: 14px;
    justify-content: space-between;
    background-color: #f1f3f5;
    color: #a3a3a3;
    margin: 10px 0;
    span {
      position: relative;
      padding-left: 12px;
      &::after {
        content: '';
        position: absolute;
        top: 50%;
        left: 0;
        width: 9px;
        height: 9px;
        box-sizing: border-box;
        border: 2px solid #368cf3;
        border-radius: 50%;
        transform: translateY(-50%);
      }
    }
    i {
      font-style: normal;
    }
    &:last-of-type {
      i {
        color: red;
      }
    }
  }
}

.voice-title {
  display: flex;
  justify-content: space-between;
  height: 56px;
  align-items: center;

  div {
    span {
      background-color: #3cc261;
      cursor: pointer;
      padding: 5px 15px;
      margin: 0 10px;
      color: #fff;
      border-radius: 2px;
      &:last-child {
        background-color: #d07473;
      }
    }
  }
}
.helloCss {
  height: 52px;
  display: flex;
  box-sizing: border-box;
  padding: 0 20px;
  font-size: 18px;
  color: #999a9b;
  align-items: center;
  background-color: #eaeff5;
  border-radius: 2px;
}
.userInfo {
  box-sizing: border-box;
  padding: 8px 0;
  h2 {
    color: #3c3c3c;
    padding: 10px 0;
  }
  div {
    box-sizing: border-box;
    padding: 16px 8px;
    background-color: #ededed;
    border-radius: 4px;
    p {
      line-height: 2;
      color: #5e5e5e;
    }
  }
}
.send-btn {
  height: 88px;
  border: 1px solid #e7e7e7;
  box-sizing: border-box;
  padding: 0 10px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  cursor: pointer;
  span {
    display: inline-block;
    padding: 8px 20px;
    background-color: #3cc261;
    color: #fff;
    border-radius: 4px;
  }
}

.YYcontent {
  flex: 1;
  height: 100%;
  max-height: 45vh;
  width: 100%;
  overflow-y: auto;
  border-radius: 4px;
}

.YYcontent img {
  width: 25px;
  height: 25px;
  display: inline-block;
  border-radius: 50%;
}

.YYcontent ul {
  padding: 0 10px;
}

.YYcontent ul li {
  width: 100%;
  list-style: none;
  align-items: flex-start;
  display: flex;
  padding: 10px 0px;
}

.contextlef {
  width: 100%;
  justify-content: flex-start;
}

.contextrig {
  justify-content: flex-end;
}

.YYcontent li p {
  padding: 5px 5px;
  background-color: #fff;
  border-radius: 5px;
  font-size: 18px;
  max-width: 35%;
  width: 35%;
  color: #303133;
  display: inline-block;
  line-height: 1.3;
}

.contextrig p {
  align-self: flex-end;
  /* background-color: #e4e4e4 !important; */
  color: #333 !important;
}
.contextrig span {
  align-self: flex-end;
}
.YYcontentCSS {
  flex: 1;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  width: 100%;
}

.YYcontent::-webkit-scrollbar {
  /*滚动条整体样式*/
  width: 4px; /*高宽分别对应横竖滚动条的尺寸*/
  height: 1px;
}
.YYcontent::-webkit-scrollbar-thumb {
  /*滚动条里面小方块*/
  border-radius: 4px;
  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  background: #535353;
}
.YYcontent::-webkit-scrollbar-track {
  /*滚动条里面轨道*/
  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  border-radius: 4px;
  background: #ededed;
}

.voice-btn > span {
  background-color: #368cf3;
  display: inline-block;
  padding: 8px 14px;
  color: #fff;
  border-radius: 4px;
  cursor: pointer;
}
.voice-btn .spanCss {
  background-color: #999a9b;
}
</style>
